package com.imooc.demo.web;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.imooc.demo.config.appid.UserConstantInterface;

import com.imooc.demo.entity.*;
import com.imooc.demo.service.*;
import com.imooc.demo.util.HttpClientUtil;
import com.imooc.demo.util.IMoocJSONResult;
import com.imooc.demo.util.OrderIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    UserAddressInfoService userAddressInfoService;
    @Autowired
    SendService sendService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    WorkerService workerService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Value("${uploadFile.h-upload}")
    private String uploadFileHupload;
    @Value("${uploadFile.w-upload}")
    private String uploadFileWupload;



    @ResponseBody
    @RequestMapping(value = "/upload")
    public Map<String, Object> upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException{
        // 封装返回小程序
        Map<String, Object> result = new HashMap<>();
        String path = null;
        //////图片访问路径
        String fileServerPath;

        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            //String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())||"JPEG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    //String realPath = request.getSession().getServletContext().getRealPath("/");
                    String realPath=uploadFileLocation+uploadFileWupload;
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;

                    //////////////////设置访问路径
                    //basePath拼接完成后，形如：http://192.168.1.20:8080/fileServer
                    /*String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                    fileServerPath = basePath + resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + trueFileName;
                    System.out.println("文件访问路径：" +   fileServerPath);*/

                    fileServerPath = resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + uploadFileWupload.substring(0, uploadFileWupload.lastIndexOf("/") + 1) + trueFileName;
                    System.out.println("文件访问路径：" + fileServerPath);


                    ////////////////////
                    // 设置存放图片文件的路径
                    path = realPath  + trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");
                }else {
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    result.put("url", null);
                    return result;
                }
            }else {
                logger.info("文件类型为空");
                result.put("url", null);
                return result;
            }
        }else {
            logger.info("没有找到相对应的文件");
            result.put("url", null);
            return result;
        }
        result.put("url",fileServerPath);
        return result;


    }





    @PostMapping("/orderinsert")
    public Map<String, Object> orderInsert(@RequestParam("serviceTime") String serviceTime,
                                       @RequestParam("addressId") Integer addressId,
                                       @RequestParam("orderAmount") BigDecimal orderAmount,
                                       @RequestParam("orderRemark") String orderRemark,
                                       @RequestParam("category2Id") Integer category2Id
                                       ,
                                       @RequestParam("imageList") String imageList) {

        // 封装返回小程序
        Map<String, Object> result = new HashMap<>();

            System.out.println("进来了");
            System.out.println("图片："+imageList);
            Order insert_order = new Order();
            String orderId = OrderIdGenerator.get();
            insert_order.setOrderId(orderId);
            insert_order.setServiceTime(serviceTime);
            insert_order.setAddressId(addressId);
            insert_order.setOrderAmount(orderAmount);
            insert_order.setOrderRemark(orderRemark);
            insert_order.setPicture(imageList);


            System.out.println("insert_order:"+insert_order.toString());
            // 添加到数据库
        Boolean flag = false;

          UserInfo user = userInfoService.getUserIndex(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            if(user.getUserInfoLabel()==0){
                Boolean flag1 = orderService.orderInsert(insert_order);
                if(!flag1){
                    System.out.println("插入数据库order失败！");

                }else {
                    System.out.println("插入数据库order成功！");
                }

                OrderDetail insert_orderDetail = new OrderDetail();
                insert_orderDetail.setOrderId(orderId);
                insert_orderDetail.setCategory2Id(category2Id);
                System.out.println("insert_orderDetail:"+insert_orderDetail.toString());
                // 添加到数据库
                Boolean flag2 = orderDetailService.orderDetailInsert(insert_orderDetail);
                if(!flag2){
                    System.out.println("插入数据库orderDetail失败！");

                }else {
                    System.out.println("插入数据库orderDetail成功！");
                }
                //Boolean flag = false;
                if(flag1==true&&flag2==true){
                    flag= true;
                }
                //插入信息
                if(flag1==true&&flag2==true) {
                    Send send = new Send();
                    send.setOrderId(orderId);
                    send.setMessageId(1);
                    send.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
                    boolean flag3 = sendService.insertSend(send);
                    if (!flag3) {
                        System.out.println("插入数据库send失败！");

                    } else {
                        System.out.println("插入数据库send成功！");
                    }
                }
                result.put("success", flag);
            }else {
                result.put("success", "fail");
            }

            /*Boolean flag1 = orderService.orderInsert(insert_order);
            if(!flag1){
                System.out.println("插入数据库order失败！");

            }else {
                System.out.println("插入数据库order成功！");
            }

            OrderDetail insert_orderDetail = new OrderDetail();
            insert_orderDetail.setOrderId(orderId);
            insert_orderDetail.setCategory2Id(category2Id);
            System.out.println("insert_orderDetail:"+insert_orderDetail.toString());
            // 添加到数据库
            Boolean flag2 = orderDetailService.orderDetailInsert(insert_orderDetail);
            if(!flag2){
                System.out.println("插入数据库orderDetail失败！");

            }else {
                System.out.println("插入数据库orderDetail成功！");
            }
        Boolean flag = false;
        if(flag1==true&&flag2==true){
            flag= true;
            }
        //插入信息
        if(flag1==true&&flag2==true) {
            Send send = new Send();
            send.setOrderId(orderId);
            send.setMessageId(1);
            send.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            boolean flag3 = sendService.insertSend(send);
            if (!flag3) {
                System.out.println("插入数据库send失败！");

            } else {
                System.out.println("插入数据库send成功！");
            }
        }*/


        // 封装返回小程序
       //Map<String, Object> result = new HashMap<>();

        //result.put("success", flag);
       // result.put("openid", userOpenid);

        //System.out.println("userOpenid:"+userOpenid);



        return  result;

    }

    //通过openid获取订单信息
    @RequestMapping(value = "findorderbyopenid",method = RequestMethod.GET)
    private  Map<String,Object>  findOrderByOpenid(String buyerOpenid,Integer orderStatus){
        /*Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orderList= orderService.findOrderByOpenid(buyerOpenid, orderStatus);
        if(orderList!=null){

            System.out.println(orderList);
        }
        System.out.println(orderList);
        modelMap.put("orderList",orderList);
        return modelMap;*/
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orderList= orderService.personOrder(buyerOpenid, orderStatus);
        if(orderList!=null){
            for(int i =0;i<orderList.size();i++){
                Worker worker = workerService.getWorkerById(orderList.get(i).getWorkerId());
                if(worker!=null){
                    orderList.get(i).setWorker(worker);
                }

            }

        }
        System.out.println(orderList);
        modelMap.put("orderList",orderList);
        return modelMap;

    }

    //通过orderid获取订单信息
    @RequestMapping(value = "findorderuserinfo",method = RequestMethod.GET)
    private  Map<String,Object>  findOrderUserInfo(@RequestParam("orderId") String orderId){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orderList= orderService.findOrderByOrderId(orderId);
        Order order =orderService.findOrderDetail(orderId);
        Worker worker = workerService.getWorkerById(order.getWorkerId());
        modelMap.put("worker",worker);
        modelMap.put("orderList",orderList);
        return modelMap;
    }
   /* @RequestMapping(value = "findorderuserinfo",method = RequestMethod.GET)
    private  Map<String,Object>  findOrderUserInfo( @RequestParam("buyerOpenid") String buyerOpenid,
                                                    @RequestParam("orderId") String orderId){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orderList= orderService.findOrderUserInfo(buyerOpenid, orderId);
        modelMap.put("orderList",orderList);
        return modelMap;
    }*/


    //用户删除订单
    @RequestMapping(value = "/cancel",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object>  cancel(@RequestParam("orderId") String orderId) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Order order = orderService.findOrderDetail(orderId);

        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("success",orderService.cancel(order));
        /////////////////////////////////////////////////////////////////插入信息
        if(orderService.cancel(order)) {
            Integer addressId = order.getAddressId();
            Send send = new Send();
            send.setOrderId(orderId);
            send.setMessageId(4);
            send.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            boolean flag3 = sendService.insertSend(send);
            if (!flag3) {
                System.out.println("插入数据库send失败！");

            } else {
                System.out.println("插入数据库send成功！");
            }
        }
        ///////////////////////////////////////////////////////
        return modelMap;
    }


    //根据地址查订单
    @RequestMapping(value = "/findorderbyaddressarea",method = RequestMethod.GET)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> findOrderByAddressArea(@RequestParam("addressArea")String addressArea,
                                                       @RequestParam("addressDetail") String addressDetail,
                                                       @RequestParam("category10Id") Integer category10Id) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orders = orderService.findOrderByAddressArea(addressArea,addressDetail,category10Id);
        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("orders",orders);
        return modelMap;
    }

    //接单
    @RequestMapping(value = "/jiedan",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object>  jieDan(@RequestParam("orderId") String orderId,
                                        @RequestParam("workerOpenid") String workerOpenid
                                        ) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Order order = orderService.findOrderDetail(orderId);
        System.out.println(order);
        Worker worker = workerService.getWorker(workerOpenid);
        System.out.println(worker);
        if(worker!=null){
            if(worker.getScore().compareTo(new BigDecimal(2.50))>=0){
                if(worker.getIsAllowed()==0){
                    order.setWorkerId(worker.getId());
                    //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
                    modelMap.put("success",orderService.jieDan(order));
                }else {
                    modelMap.put("success","fail");
                }

            }else {
                modelMap.put("success","null");
            }


        }else {
            modelMap.put("success",false);
        }




        /////////////////////////////////////////////////////////////////插入信息
        if(worker!=null&&worker.getScore().compareTo(new BigDecimal(2.50))>=0) {
            Integer addressId = order.getAddressId();
            Send send1 = new Send();
            send1.setOrderId(orderId);
            send1.setMessageId(2);
            send1.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            boolean flag3 = sendService.insertSend(send1);
            Send send2 = new Send();
            send2.setOrderId(orderId);
            send2.setMessageId(7);
            send2.setBuyerOpenid(workerOpenid);
            boolean flag4 = sendService.insertSend(send2);
            if (!flag3&!flag4) {
                System.out.println("插入数据库send失败！");

            } else {
                System.out.println("插入数据库send成功！");
            }
        }
        ///////////////////////////////////////////////////////

        return modelMap;
    }


    //工匠取消订单
    @RequestMapping(value = "/workercancel",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> workercancel(@RequestParam("orderId") String orderId,
                                             @RequestParam("workerRemark") String workerRemark) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Order order = orderService.findOrderDetail(orderId);
        order.setWorkerRemark(workerRemark);
        System.out.println("workerRemark:"+workerRemark);
        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("success",orderService.workercancel(order));


        /////////////////////////////////////////////////////////////////插入信息
        if(orderService.workercancel(order)) {
            Integer addressId = order.getAddressId();
            Send send1 = new Send();
            send1.setOrderId(orderId);
            send1.setMessageId(5);
            send1.setBuyerOpenid(workerService.getWorkerById(order.getWorkerId()).getOpenId());
            boolean flag3 = sendService.insertSend(send1);
            //////
            Send send2 = new Send();
            send2.setOrderId(orderId);
            send2.setMessageId(4);
            send2.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            boolean flag4 = sendService.insertSend(send2);

            if (!flag3&&!flag4) {
                System.out.println("插入数据库send失败！");

            } else {
                System.out.println("插入数据库send成功！");
            }
        }
        ///////////////////////////////////////////////////////


        return modelMap;
    }


    //根据工匠查订单
    @RequestMapping(value = "/findorderbyworker",method = RequestMethod.GET)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> findOrderByWorker(@RequestParam("workerOpenid") String workerOpenid,
                                                  @RequestParam("orderStatus") Integer orderStatus) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orders = orderService.findOrderByWorker(workerOpenid,orderStatus);
        System.out.println(orders);
        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("orders",orders);
        return modelMap;
    }

    //完成订单
    @RequestMapping(value = "/finish",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object>  finish(@RequestParam("orderId") String orderId) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        Order order = orderService.findOrderDetail(orderId);
        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("success",orderService.finish(order));


        /////////////////////////////////////////////////////////////////插入信息
        if(orderService.finish(order)) {
            Integer addressId = order.getAddressId();
            Send send1 = new Send();
            send1.setOrderId(orderId);
            send1.setMessageId(6);
            send1.setBuyerOpenid(workerService.getWorkerById(order.getWorkerId()).getOpenId());
            boolean flag3 = sendService.insertSend(send1);
            //////
            Send send2 = new Send();
            send2.setOrderId(orderId);
            send2.setMessageId(3);
            send2.setBuyerOpenid(userAddressInfoService.getAddressinfoById(addressId).getBuyerOpenid());
            boolean flag4 = sendService.insertSend(send2);

            if (!flag3&&!flag4) {
                System.out.println("插入数据库send失败！");

            } else {
                System.out.println("插入数据库send成功！");
            }
        }
        ///////////////////////////////////////////////////////


        return modelMap;
    }



    //        //查找某人所有订单
    @RequestMapping(value = "findallorderbyopenid",method = RequestMethod.GET)
    private  Map<String,Object>  findAllOrderByOpenid( @RequestParam("buyerOpenid") String buyerOpenid){
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        List<Order> orderList= orderService.findAllOrderByOpenid(buyerOpenid);
        modelMap.put("orderList",orderList);
        return modelMap;
    }






    //根据地址查订单
   /* @RequestMapping(value = "/findorderbymap",method = RequestMethod.GET)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> findOrderByMap(@RequestParam("addressArea")String addressArea


    ) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        //UserInfo userInfo = userInfoService.getUserInfo(buyerOpenid);
       // String addressArea = userInfo.getUserCity();
        List<Order> orders = orderService.findOrderByAddressArea(addressArea,"",);
        //修改种类信息 ，"success"保存操作状态，如category1Service.modifyCategory1(category1)操作成功返回true，否则false
        modelMap.put("orders",orders);
        return modelMap;
    }*/



    /////////////////用户评分
    @RequestMapping(value = "/setpingfen",method = RequestMethod.POST)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object>  setPingFen(@RequestParam("orderId") String orderId,
                                            @RequestParam("pingFen") BigDecimal pingFen,
                                            @RequestParam("id") Integer id) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
        System.out.println("orderId："+orderId);
        Order order = orderService.findOrderDetail(orderId);
        order.setPingFen(pingFen);
        System.out.println("搜索结果："+order);
        if(orderService.setPingFen(order)){
            List<Order> orders=orderService.getAllPingFen();

            BigDecimal score=new BigDecimal("0.00");
            BigDecimal baseScore=new BigDecimal("100.00");
            BigDecimal size=new BigDecimal(orders.size()+20);
            System.out.println("orders.size()："+size);
            for(int i=0;i<orders.size();i++){
                score = score.add(orders.get(i).getPingFen());
                System.out.println("orders.get(i).getPingFen()："+orders.get(i).getPingFen());
            }
            System.out.println("score："+score);
            score = score.add(baseScore).divide(size,2,BigDecimal.ROUND_HALF_UP);
            System.out.println("score："+score);
            Worker worker=workerService.getWorkerById(id);
            if(worker!=null){
                score=score.add(worker.getScore()).divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP);
                worker.setScore(score);
                modelMap.put("success",workerService.updateScoreById( worker));


            }

        }

       // modelMap.put("success",);

        return modelMap;
    }



    //获取订单评分
    @RequestMapping(value = "/getorderpingfen",method = RequestMethod.GET)
    //@RequestBody标识接收的内容除了xwww from url encoding 编码内容之外的一些内容，如json，xml等
    private  Map<String,Object> getOrderPingFen(@RequestParam("orderId")String orderId) {
        Map<String,Object>  modelMap = new HashMap<String ,Object>();
       Order order= orderService.findOrderDetail(orderId);
       if(order.getPingFen()!=null){
           modelMap.put("orderPingFen",order.getPingFen());

       }else {
           modelMap.put("orderPingFen",null);
       }



        return modelMap;
    }










}
